package com.nbicc.file.utils;

import com.nbicc.common.MyValues;
import com.nbicc.common.utils.CommonUtils;
import com.nbicc.common.utils.OSUtils;
import com.nbicc.file.bo.FileDesc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Calendar;

@Component
public class FileUtils {

    @Autowired
    private MyValues myValues;

    private String rootPath = null;

    /**
     * 获取在不同操作系统下的文件存储根路径
     * @return
     */
    public String rootPath(){
        if(rootPath == null){
            switch (OSUtils.getOSType()) {
                case "win":
                    rootPath = myValues.getWinfilepath();
                    break;
                case "linux":
                    rootPath = myValues.getLinuxfilepath();
                    break;
                case "mac":
                    rootPath = myValues.getMacfilepath();
                    break;
                default:
                    throw new RuntimeException("无法识别OS类型");
            }
        }
        return  rootPath;
    }

    /**
     * 按日期生成存储路径(文件夹)
     * 每天上传的文件都放在不同文件夹下
     * @return
     */
    public String relativeFolder(){
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH)+1;
        int day = cal.get(Calendar.DATE);
        String ymd = ""+year+month+day;

        String path = File.separator + ymd ;
        return path;
    }

    public void iniRequestHeader(FileDesc fileDesc , HttpServletRequest request){
        iniSegment(fileDesc , request);
    }

    public void iniSegment(FileDesc fileDesc , HttpServletRequest request) {
        fileDesc.setSegment(false);
        fileDesc.setPos(-1);
        fileDesc.setLength(-1);

        if(request != null){
            if(request.getHeader("Segment") != null){
                fileDesc.setSegment(CommonUtils.int2boolean(request.getHeader("Segment")));
            }
            if (request.getHeader("Range") != null) {			//如果http下载头中  不包含range字段  则为全部
                segmentSetting(fileDesc , request.getHeader("Range"));
            }
        }
    }

    private void segmentSetting(FileDesc fileDesc , String range) {
        long pos = -1;
        long length = -1;
        if (range.startsWith("-")){
            length = Long.parseLong(range.substring(1));
        } else if (range.endsWith("-")){
            pos = Long.parseLong(range.replace("-", ""));
        } else{
            String[] se = range.split("-");
            pos = Long.parseLong(se[0]);
            length = Long.parseLong(se[1]);
        }
        fileDesc.setPos(pos);
        fileDesc.setLength(length);
    }

}
